<template>
  <section class="f-dails">
    <div class="w-card my-content-box" v-if="!isDetail">
      <div class="title-box">
        <span class="title-text">代理商列表</span>
        <el-button style="margin-left:auto;" type="warning" plain @click="exportHandle(null)">全部导出</el-button>
      </div>
      <div class="my-search-box">
        <div>
          <span>商户名称：</span>
          <el-input v-model="searchForm.shopName" clearable placeholder="请输入商户名称" />
        </div>
        <div>
          <span>邀请码：</span>
          <el-input v-model="searchForm.shopCode" clearable placeholder="请输入商户邀请码" />
        </div>
        <div>
          <span>分销层级：</span>
          <el-input v-model="searchForm.level" clearable placeholder="请输入分销层级" />
        </div>
        <div>
          <span>商户状态：</span>
          <el-select v-model="searchForm.operationalStatus">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
      </div>
      <div class="my-search-box">
        <div>
          <span>商户类型：</span>
          <el-select v-model="searchForm.auditStatus">
            <el-option v-for="item in auditStatusOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
        <div>
          <span>实名状态：</span>
          <el-select v-model="searchForm.certificationStatus">
            <el-option v-for="item in smOptions" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </div>
        <div class="datebox">
          <span>创建时间：</span>
          <el-date-picker v-model="searchForm.date" type="datetimerange" value-format="x" start-placeholder="开始时间"
            end-placeholder="结束时间" @change="(e) => {console.log(e)}" />
        </div>
        <el-button @click="searchHandle" type="primary">查询</el-button>
        <el-button style="margin-left:0;" @click="resetHandle">重置</el-button>
      </div>
      <div class="my-table-box">
        <el-table :height="tableHeight" :header-cell-style="{background:'#d6dee5',color:'#000000',fontSize:'14px'}"
          :cell-style="{fontSize:'12px',color:'#7b7b7d'}" :data="tableData" @selection-change="handleSelectionChange" stripe>
          <el-table-column type="index" width="55" label="序号" align="center" />
          <el-table-column type="selection" width="55" />
          <el-table-column prop="shopName" label="商户名称" align="center">
            <template v-slot="scope">
              <el-link style="font-size:12px" type="primary"
                @click="lookDetail(scope.row.shopId)">{{ scope.row.shopName || '' }}</el-link>
            </template>
          </el-table-column>
          <el-table-column prop="shopCode" label="商户邀请码" align="center">
            <template v-slot="scope">
              {{ scope.row.shopCode || '' }}
            </template>
          </el-table-column>
          <!-- <el-table-column prop="codeStatus" label="邀请码状态" align="center">
          <template v-slot="scope">
            {{ scope.row.codeStatus == 0 ? '冻结' : scope.row.codeStatus == 1 ? '正常' : '' }}
          </template>
        </el-table-column> -->
          <el-table-column prop="auditStatus" label="商户类型" align="center" width="80">
            <template v-slot="scope">
              {{ scope.row.auditStatus == 1 ? '个人' : scope.row.auditStatus == 2 ? '公司' : '' }}
            </template>
          </el-table-column>
          <el-table-column prop="vipLevel" label="店铺等级" align="center" width="80">
            <template v-slot="scope">
              {{ scope.row.vipLevel || '' }}
            </template>
          </el-table-column>
          <el-table-column prop="level" label="分销层级" align="center" width="80">
            <template v-slot="scope">
              {{ scope.row.level || '' }}
            </template>
          </el-table-column>
          <el-table-column prop="certificationStatus" label="实名状态" align="center" width="100">
            <template v-slot="scope">
              {{ scope.row.certificationStatus == 0 ? '未实名' : scope.row.certificationStatus == 1 ? '已实名' : '' }}
            </template>
          </el-table-column>
          <el-table-column prop="createTime" label="创建时间" align="center" width="180">
            <template v-slot="scope">
              {{ scope.row.createTime ? getDateTime(scope.row.createTime)[6] : '' }}
            </template>
          </el-table-column>
          <el-table-column prop="supplierShopName" label="上级代理商" align="center">
            <template v-slot="scope">
              {{ scope.row.supplierShopName || '' }}
            </template>
          </el-table-column>
          <el-table-column prop="operationalStatus" label="商户状态" align="center">
            <template v-slot="scope">
              <span :class="'state'+scope.row.operationalStatus"></span>
              {{ scope.row.operationalStatus == 0 ? '拉黑' : scope.row.operationalStatus == 1 ? '正常' : scope.row.operationalStatus == 2 ? '邀请码冻结' : '' }}
            </template>
          </el-table-column>
          <!-- <el-table-column prop="Operations" label="操作" align="center" width="160" fixed="right">
            <template v-slot="scope">
              <div class="table-handle-box">
                <el-link v-show="scope.row.operationalStatus != 2" style="font-size:12px" type="primary"
                  @click="handleClick(1,scope.row)">邀请码冻结</el-link>
                <el-link v-show="scope.row.operationalStatus == 2" style="font-size:12px" type="danger"
                  @click="handleClick(2,scope.row)">邀请码解冻</el-link>
                <el-link v-show="scope.row.operationalStatus != 0" style="font-size:12px"
                  @click="handleClick(3,scope.row)">拉黑</el-link>
                <el-link v-show="scope.row.operationalStatus == 0" style="font-size:12px" type="danger"
                  @click="handleClick(4,scope.row)">解除拉黑</el-link>
              </div>
            </template>
          </el-table-column> -->
        </el-table>
        <div class="my-table-footer">
          <div>
            <!-- <el-button :size="btnSize" :disabled="chooseList.length == 0" plain type="danger"
              @click="handleClick(5,chooseList)">邀请码冻结</el-button>
            <el-button :size="btnSize" :disabled="chooseList.length == 0" plain type="primary"
              @click="handleClick(6,chooseList)">邀请码解冻</el-button>
            <el-button :size="btnSize" :disabled="chooseList.length == 0" plain type="warning"
              @click="handleClick(7,chooseList)">拉黑</el-button>
            <el-button :size="btnSize" :disabled="chooseList.length == 0" plain type="primary"
              @click="handleClick(8,chooseList)">解除拉黑</el-button> -->
            <el-button :size="btnSize" :disabled="chooseList.length == 0" plain type=""
              @click="exportHandle(chooseList)">导出</el-button>
          </div>
          <el-pagination style="margin-left:auto;" v-model:currentPage="page" v-model:page-size="size"
            :page-sizes="[10, 20, 50, 100]" small :background="true" layout="total, sizes, prev, pager, next, jumper"
            :total="total" @size-change="handleSizeChange" @current-change="handleCurrentChange" />
        </div>
      </div>
    </div>
    <confirm-pass-vue ref="confirmPassVueRef" @verification="verification" />

    <router-view v-if="isDetail"></router-view>
  </section>
</template>

<script>
import { onMounted, reactive, ref, toRefs, watch } from 'vue'
import { getWindowWidthAndHeight, warningDeal, getDateTime, successDeal, BlobDownLoad } from '@/utils/utils'
import { useRouter, useRoute } from 'vue-router'
import api from './api'
import confirmPassVue from '@/components/confirmPass.vue'

export default {
  components: {
    confirmPassVue,
  },
  setup() {
    const route = useRoute()
    const router = useRouter()

    const confirmPassVueRef = ref(null)

    const state = reactive({
      isDetail: false,
      loading: false,
      handleType: null,
      handleData: null,
      btnSize: 'small',
      page: 1,
      size: 10,
      total: 0,
      tableHeight: 0,
      searchForm: {},
      tableData: [],
      chooseList: [],
      statusOptions: [
        {
          value: 1,
          label: '正常',
        },
        {
          value: 0,
          label: '拉黑',
        },
        {
          value: 2,
          label: '邀请码冻结',
        },
      ],
      auditStatusOptions: [
        {
          value: 1,
          label: '个人',
        },
        {
          value: 2,
          label: '公司',
        },
      ],
      smOptions: [
        {
          value: 0,
          label: '未实名',
        },
        {
          value: 1,
          label: '已实名',
        },
      ],
      vipLevelOptions: [
        {
          value: 1,
          label: '普通会员',
        },
        {
          value: 2,
          label: '超级会员',
        },
      ],
    })

    watch(() => route.path, (newVal, oldVal) => {
      setIsDetail()
    })

    function setIsDetail() {
      state.isDetail = (route.path != '/shopManage/dails')
      getTableData()
    }

    function searchHandle() {
      state.page = 1
      getTableData()
    }

    function resetHandle() {
      state.searchForm = {}
      searchHandle()
    }

    function getTableData() {
      const obj = {
        page: state.page,
        size: state.size,
        ...state.searchForm,
        startTime: state.searchForm.date && state.searchForm.date[0],
        endTime: state.searchForm.date && state.searchForm.date[1],
      }
      api.shopSearch(obj).then(res => {
        if (res.code == '200') {
          state.tableData = res.data.records
          state.total = res.data.total
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function handleSelectionChange(e) {
      state.chooseList = e
    }

    function handleCurrentChange(e) {
      state.page = e
      getTableData()
    }

    function handleSizeChange(e) {
      state.size = e
      getTableData()
    }

    function lookDetail(shopId) {
      router.push({ path: '/shopManage/dails/detail', query: { shopId } })
    }

    function handleClick(type, data) {
      state.handleType = type
      state.handleData = data
      let title = ''
      let msg = ''
      switch (type) {
        case 1:
          //邀请码冻结
          title = '是否冻结该商户的邀请码？'
          msg = '商户邀请码冻结后，将不能发展下游代理商'
          break
        case 2:
          //邀请码解冻
          title = '是否解除冻结该商户的邀请码？'
          msg = '商户邀请码解除冻结后，可以继续发展下游代理商'
          break
        case 3:
          //拉黑
          title = '是否拉黑该商户？'
          msg = '商户拉黑后，将无法登录使用精灵伙伴App'
          break
        case 4:
          //解除拉黑
          title = '是否解除拉黑该商户？'
          msg = '商户解除拉黑后，可以正常登录使用精灵伙伴App'
          break
        case 5:
          //邀请码冻结
          title = '是否冻结该商户的邀请码？'
          msg = '商户邀请码冻结后，将不能发展下游代理商'
          break
        case 6:
          //邀请码解冻
          title = '是否解除冻结该商户的邀请码？'
          msg = '商户邀请码解除冻结后，可以继续发展下游代理商'
          break
        case 7:
          //拉黑
          title = '是否拉黑该商户？'
          msg = '商户拉黑后，将无法登录使用精灵伙伴App'
          break
        case 8:
          //解除拉黑
          title = '是否解除拉黑该商户？'
          msg = '商户解除拉黑后，可以正常登录使用精灵伙伴App'
          break
      }
      confirmPassVueRef.value.dialogShow(title, msg, false)
    }

    function verification() {
      let myArr = []
      switch (state.handleType) {
        case 1:
          dongAjieHandle([state.handleData.shopId], 2)
          break
        case 2:
          dongAjieHandle([state.handleData.shopId], 1)
          break
        case 3:
          heiAjieHandle([state.handleData.shopId], 0)
          break
        case 4:
          heiAjieHandle([state.handleData.shopId], 1)
          break
        case 5:
          state.handleData && state.handleData.map(item => {
            myArr.push(item.shopId)
          })
          dongAjieHandle(myArr, 2)
          break
        case 6:
          state.handleData && state.handleData.map(item => {
            myArr.push(item.shopId)
          })
          dongAjieHandle(myArr, 1)
          break
        case 7:
          state.handleData && state.handleData.map(item => {
            myArr.push(item.shopId)
          })
          heiAjieHandle(myArr, 0)
          break
        case 8:
          state.handleData && state.handleData.map(item => {
            myArr.push(item.shopId)
          })
          heiAjieHandle(myArr, 1)
          break
      }
    }

    function dongAjieHandle(shopIds, operationalStatus) {
      const obj = {
        shopIds,
        operationalStatus,
      }
      api.shopStateBatchUpdate(obj).then(res => {
        if (res.code == '200') {
          successDeal(res.msg)
          getTableData()
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function heiAjieHandle(shopIds, operationalStatus) {
      const obj = {
        shopIds,
        operationalStatus,
      }
      api.shopStateBatchUpdate(obj).then(res => {
        if (res.code == '200') {
          successDeal(res.msg)
          getTableData()
        } else {
          warningDeal(res.msg)
        }
      }).catch(err => {
        console.log(err)
      })
    }

    function exportHandle(data = null) {
      if (data) {
        const obj = {
          exportInfoList: data,
          responseType: 'blob',
        }
        api.shopExportAppoint(obj).then(res => {
          const _fileName = decodeURIComponent(res.headers['content-disposition'].split(';')[1].split('=')[1])
          BlobDownLoad(res, _fileName)
        }).catch(err => {
          console.log(err)
        })
      } else {
        const obj = {
          responseType: 'blob',
        }
        api.shopExportAll(obj).then(res => {
          const _fileName = decodeURIComponent(res.headers['content-disposition'].split(';')[1].split('=')[1])
          BlobDownLoad(res, _fileName)
        }).catch(err => {
          console.log(err)
        })
      }
    }

    function vipLevelChange(data) {
      if (state.loading) return
      state.loading = true
      const obj = {
        shopId: data.shopId,
        vipLevel: data.vipLevel,
      }
      api.manageShop(obj).then(res => {
        if (res.code == '200') {
          successDeal(res.msg)
          getTableData()
        } else {
          warningDeal(res.msg)
        }
        state.loading = false
      }).catch(err => {
        console.log(err)
        state.loading = false
      })
    }

    onMounted(() => {
      let winHeight = getWindowWidthAndHeight()
      state.tableHeight = winHeight.windowHeight - 340
      window.addEventListener('resize', (e) => {
        if (document.documentElement.clientWidth < 1150) {
          state.btnSize = 'small'
        } else {
          state.btnSize = ''
        }
      })
      setIsDetail()
    })

    return {
      ...toRefs(state),
      confirmPassVueRef,
      exportHandle,
      searchHandle,
      resetHandle,
      handleSelectionChange,
      lookDetail,
      handleCurrentChange,
      handleSizeChange,
      getDateTime,
      handleClick,
      verification,
      vipLevelChange,
    }
  }
}
</script>

<style lang="scss" scoped>
.my-content-box {
  box-sizing: border-box;
  padding: 20px;

  > .title-box {
    display: flex;
    align-items: center;

    > .title-text {
      font-size: 16px;
      font-weight: bold;
    }
  }

  .my-search-box {
    box-sizing: border-box;
    padding: 20px;
    padding-bottom: 0;
    font-size: 14px;
    display: flex;
    align-items: center;
    gap: 10px;

    > div {
      width: 300px;
      display: flex;
      align-items: center;

      > span {
        flex-shrink: 0;
      }
    }

    .datebox {
      width: 400px;
    }
  }

  .my-table-box {
    margin-top: 20px;

    .table-handle-box {
      display: flex;
      justify-content: space-around;
      align-items: center;
    }

    .my-table-footer {
      display: flex;
      align-items: center;
      margin-top: 10px;
      flex-wrap: wrap;
      gap: 10px;
    }
  }
}
</style>